package com.glory.dgcpcpda.activity.check;

import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.CheckDescListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.entity.CheckSheetEntity;
import com.glory.dgcpcpda.entity.MesReturnEntity;
import com.glory.dgcpcpda.entity.SheetInfoEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 待处理
 */
public class CheckDescActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.rvCheckDescList)
    RecyclerView rvCheckDescList;
    @BindView(R.id.etComment)
    FreeUI_ClearEditText etComment;
    @BindView(R.id.tvCheckID)
    TextView tvCheckID;
    @BindView(R.id.tvLotID)
    TextView tvLotID;
    @BindView(R.id.tvEqpID)
    TextView tvEqpID;
    @BindView(R.id.tvCheckTime1)
    TextView tvCheckTime1;
    @BindView(R.id.tvClazz)
    TextView tvClazz;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvResult)
    TextView tvResult;
    @BindView(R.id.tvComment)
    TextView tvComment;
    @BindView(R.id.flCheckTime)
    FrameLayout flCheckTime;
    @BindView(R.id.ivCheckTime)
    ImageView ivCheckTime;
    @BindView(R.id.tvCheckTime)
    TextView tvCheckTime;
    @BindView(R.id.llCheckTime)
    LinearLayout llCheckTime;
    private CheckSheetEntity mData;
    private CheckDescListAdapter mAdapter;
    private String mObjectRRN = "";
    private String mChecktime;
    private String EQUIPMENTID = "";
    private String LOTID = "";
    private List<String> mCheckTimeList;
    private FreeUI_GeneralPop mCheckTimePop;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_check_desc;
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        mData = (CheckSheetEntity) bundle.getSerializable("SHEETDATA");
        mObjectRRN = getIntent().getExtras().getString("OBJECTRRN");
        mChecktime = getIntent().getExtras().getString("CHECKTIME");
        EQUIPMENTID = getIntent().getExtras().getString("EQUIPMENTID");
        LOTID = getIntent().getExtras().getString("LOTID");
//        tvResult.setVisibility(mChecktime.equals("巡检") ? View.VISIBLE : View.GONE);
        tvComment.setVisibility(mChecktime.equals("巡检") ? View.VISIBLE : View.GONE);
        if(mChecktime.equals("交接班检")){
            tvComment.setVisibility(View.VISIBLE);
        }
        llCheckTime.setVisibility(mChecktime.equals("巡检") ? View.GONE : View.VISIBLE);
        List<SheetInfoEntity.SheetCheckTableLineEntity> sheetchecktablelines = mData.getSHEETLIST().get(0).getSHEETCHECKTABLELINES();
        tvCheckID.setText(mObjectRRN);
        tvCheckTime1.setText(mData.getSHEETTIME());
        tvClazz.setText(mData.getSHIFT());
        tvEqpID.setText(mData.getEQUIPMENTID());
        tvLotID.setText(LOTID);
        tvBaseSubmit.setText("提交");
        tvTitle.setText("点检表单详情");
        setMainLayout(llMain);
        initRecyclerView(rvCheckDescList, this);
        mAdapter = new CheckDescListAdapter(mChecktime.equals("巡检") ? R.layout.adapter_check_desc_inspection : R.layout.adapter_check_desc, null, mChecktime);
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.isFirstOnly(true);
        rvCheckDescList.setAdapter(mAdapter);
        mCheckTimeList = new ArrayList<>();
        mCheckTimeList.add("调机点检");
        mCheckTimeList.add("改机点检");
        getCheckData(sheetchecktablelines);
    }

    private void getCheckData(List<SheetInfoEntity.SheetCheckTableLineEntity> sheetchecktablelines) {
        List<SheetInfoEntity.SheetCheckTableLineEntity> mEapData = new ArrayList<>();
        Iterator<SheetInfoEntity.SheetCheckTableLineEntity> iterator = sheetchecktablelines.iterator();
        while (iterator.hasNext()) {
            SheetInfoEntity.SheetCheckTableLineEntity next = iterator.next();
            if (!next.getRESERVED2().equals("")) {
                mEapData.add(next);
                iterator.remove();
            }

        }
        if (mEapData.size() > 0) {
            List<EAPCheckEntity.CheckEntity> checkList = new ArrayList<>();
            for (SheetInfoEntity.SheetCheckTableLineEntity entity : mEapData) {
                EAPCheckEntity.CheckEntity checkEntity = new EAPCheckEntity.CheckEntity(entity.getRESERVED2());
                checkList.add(checkEntity);
            }

            FreeUI_EntityCallBack<BaseResponseBean<EAPCheckEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EAPCheckEntity>>
                    (new TypeToken<BaseResponseBean<EAPCheckEntity>>() {
                    }.getType(), getSupportFragmentManager(), this) {

                @Override
                public void onSuccess(Response<BaseResponseBean<EAPCheckEntity>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                        List<EAPCheckEntity.CheckEntity> paramterlist = response.body().getResponse().getBody().getPARAMTERLIST();
                        if (paramterlist.size() <= 0) {
                            showConfirmDialog("EAP返回参数信息为空!");
                            return;
                        }
                        for (SheetInfoEntity.SheetCheckTableLineEntity entity : mEapData) {
                            for (EAPCheckEntity.CheckEntity checkEntity : paramterlist) {
                                if (entity.getRESERVED2().equals(checkEntity.getName())) {
                                    entity.setVALUE(checkEntity.getValue());
                                }
                            }
                        }
                        sheetchecktablelines.addAll(mEapData);
                        mAdapter.setNewData(sheetchecktablelines);
                    }
                    else{
                        sheetchecktablelines.addAll(mEapData);
                        mAdapter.setNewData(sheetchecktablelines);
                    }
                }

                @Override
                public void onError(Response<BaseResponseBean<EAPCheckEntity>> response) {
                    super.onError(response);
                    loadError(response.getException(), "CHECKSHEET");

                }
            };
            JsonObject map = new JsonObject();
            map.addProperty("EQPID", tvEqpID.getText().toString());
            map.add("PARAMTERLIST", new JsonParser().parse(new Gson().toJson(checkList)).getAsJsonArray());
            NetUtils.requestPostNet("CPC.GetEqpCurrentParamter", "GetEqpCurrentParamter", this, map, callBack);
        }else {
//            return sheetchecktablelines;
            mAdapter.setNewData(sheetchecktablelines);
        }

//        return null;
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvBaseSubmit,R.id.flCheckTime})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
                boolean isRESERVED8 = true;

                for (SheetInfoEntity.SheetCheckTableLineEntity data:mAdapter.getData()){
                    if(mChecktime.equals("交接班检")){
                        if(data.getVALUE().equals("")||data.getVALUE().equals(null)){
                            showToast(data.getNAME()+"对应的值不能为空",false);
                            return;
                        }
                    }
                    if(mChecktime.equals("巡检")){
                        if(data.getVALUE().equals("")&&data.getRESERVED8().equals("")){
                            showToast(data.getNAME()+"对应的值不能为空",false);
                            return;
                        }
                    }
                    if(data.getVALUE().contains("\n")||data.getVALUE().contains("\r")){
                        showConfirmDialog(data.getNAME()+"输入的值有换行符号，禁止输入换行符号，请删除！");
                        return;
                    }
                    if(data.getVALUE().contains(" ")){
                        showConfirmDialog(data.getNAME()+"输入的值有空格符号，禁止输入空格符号，请删除！");
                        return;
                    }
//                    if (data.getRESERVED8().equals("") && mChecktime.equals("巡检")){
//                        showToast("请选择检验结果",false);
//                        return;
//                    }
                }

                showSubmitDialog(() -> {
                    FreeUI_EntityCallBack<BaseResponseBean<MesReturnEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<MesReturnEntity>>
                            (new TypeToken<BaseResponseBean<MesReturnEntity>>() {
                            }.getType(), getSupportFragmentManager(), this) {

                        @Override
                        public void onSuccess(Response<BaseResponseBean<MesReturnEntity>> response) {
                            super.onSuccess(response);
                            if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
//                                if (mChecktime.equals("巡检")){
//                                    showConfirmDialog(CheckDescActivity.this, "提交成功");
//                                    return;
//                                }
                                if(response.body().getResponse().getBody().getFLAGNG().equals("NG")){
                                    showConfirmDialog(CheckDescActivity.this, response.body().getResponse().getBody().getCOMMENT());
                                }else{
                                    showConfirmDialog(CheckDescActivity.this, "提交成功");
                                }
                            }
                        }

                        @Override
                        public void onError(Response<BaseResponseBean<MesReturnEntity>> response) {
                            super.onError(response);
                            loadError(response.getException(), "CHECKSHEET");

                        }
                    };
                    JsonObject map = new JsonObject();
                    map.addProperty("ACTIONTYPE", "SAVE");
                    map.addProperty("CHECKSHEETDATARRN", mObjectRRN);
                    map.addProperty("LOTID", LOTID);
                    map.addProperty("EQUIPMENTID", EQUIPMENTID);
                    SheetInfoEntity sheetInfoEntity = mData.getSHEETLIST().get(0);
                    // 备注栏位
                    sheetInfoEntity.setCOMMENTS(etComment.getText().toString());
                    sheetInfoEntity.setSHEETCHECKTABLELINES(mAdapter.getData());
                    sheetInfoEntity.setGROUP3(tvCheckTime.getText().toString());
                    sheetInfoEntity.setEQUIPMENTID(EQUIPMENTID);
                    map.add("SHEETLIST", new JsonParser().parse(new Gson().toJson(sheetInfoEntity)).getAsJsonObject());
                    NetUtils.requestPostNet("CPC.CHECKSHEET", "CHECKSHEET", this, map, callBack);
                });
                break;
            case R.id.flCheckTime:
                if (mCheckTimePop != null) {
                    if (mCheckTimePop.isShowing()) {
                        mCheckTimePop.dismiss();
                    }
                } else {
                    mCheckTimePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flCheckTime.getWidth(), mCheckTimeList, ivCheckTime, (codeS, i) -> {
                        tvCheckTime.setText(codeS);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivCheckTime);
                mCheckTimePop.showAsDropDown(flCheckTime, 0, 0);
                break;
        }
    }

    public static class EAPCheckEntity implements Serializable {
        private String EQPID;
        private List<CheckEntity> PARAMTERLIST;

        public String getEQPID() {
            return EQPID == null ? "" : EQPID;
        }

        public void setEQPID(String EQPID) {
            this.EQPID = EQPID;
        }

        public List<CheckEntity> getPARAMTERLIST() {
            if (PARAMTERLIST == null) {
                return new ArrayList<>();
            }
            return PARAMTERLIST;
        }

        public void setPARAMTERLIST(List<CheckEntity> PARAMTERLIST) {
            this.PARAMTERLIST = PARAMTERLIST;
        }

        public static class CheckEntity implements Serializable {
            private String PARANAME;
            private String EqpType;
            private String Value;
            private String Name;

            public String getName() {
                return Name == null ? "" : Name;
            }

            public void setName(String name) {
                Name = name;
            }

            public CheckEntity(String PARANAME) {
                this.PARANAME = PARANAME;
            }

            public String getPARANAME() {
                return PARANAME == null ? "" : PARANAME;
            }

            public void setPARANAME(String PARANAME) {
                this.PARANAME = PARANAME;
            }

            public String getEqpType() {
                return EqpType == null ? "" : EqpType;
            }

            public void setEqpType(String eqpType) {
                EqpType = eqpType;
            }

            public String getValue() {
                return Value == null ? "" : Value;
            }

            public void setValue(String value) {
                Value = value;
            }
        }
    }

}
